//
//  AppDelegate.m
//  MooreDoll
//
//  Created by Joe on 2014/11/24.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "AppDelegate.h"
#import "MFSideMenu.h"
#import "TelephonyInfo.h"
#import "XMPPSharedInstance.h"
#import "AFNetworkActivityIndicatorManager.h"
#import <ExternalAccessory/ExternalAccessory.h>

@interface AppDelegate ()

@end

@implementation AppDelegate





//- (CGSize)sizeForNibNamed:(NSString *)nibName
//{
//    CGSize nibSize = CGSizeZero;
//    if ([self.nibSizeDict objectForKey:nibName])
//    {
//        NSString *sizeString = [self.nibSizeDict objectForKey:nibName]; nibSize = CGSizeFromString(sizeString);
//    } else {
//        UIView *nibView = [[[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil] lastObject];
//        if (nibView != nil) {
//            nibSize = CGSizeMake(CGRectGetWidth(nibView.bounds), CGRectGetHeight(nibView.bounds));
//            [self.nibSizeDict setObject:NSStringFromCGSize(nibSize) forKey:nibName];
//        }
//    }
//    return nibSize;
//}









-(void)checkAFNetworkReachability
{
    
    NSURL *baseURL = [NSURL URLWithString:MD_SERVER_API];
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
    NSOperationQueue *operationQueue = manager.operationQueue;
    
    [manager.reachabilityManager startMonitoring];
    
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [operationQueue setSuspended:NO];

                if ([XMPPSharedInstance sharedInstance].state==2) {
                    //檢查當前的 wifi 名稱
                    if ([[TelephonyInfo currentWifiName]hasPrefix:@"MDAP"]) {
                        NSLog(@"MDAP網路");
                    }else
                    {
                        NSLog(@"跳回自己網路");
                    }
                }
                NSLog(@"有網路");

                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"無效網路");
//                [[[UIAlertView alloc]initWithTitle:@"無網路" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil]show];

            default:
                [operationQueue setSuspended:YES];
                break;
        }
    }];
    
    
    
    
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    
    //設定UINavigationBar 的背景色
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithHexString:@"FF7F0D"]];
    
    //設定UINavigationBar 的title 顏色
    NSDictionary *dict = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont fontWithName:@"ArialMT" size:20.0]};
    [[UINavigationBar appearance]setTitleTextAttributes:dict];

    //設定tabBar 顏色
    [[UITabBar appearance]setTintColor:[UIColor colorWithHexString:@"FF7F0D"]];
    
    [self checkAFNetworkReachability];

    [Language initUserLanguage];
    
    //新增左側菜單
    [AppDelegate sideMenu];
    
    return YES;
}

+(void)sideMenu
{
    
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    

    MFSideMenuContainerViewController *container = (MFSideMenuContainerViewController *)appDelegate.window.rootViewController;
    
    UITabBarController *tabBarController = [storyboard instantiateViewControllerWithIdentifier:@"tabBar"];
    
    //UINavigationController *navigationController = [storyboard instantiateViewControllerWithIdentifier:@"mainView"];
    
    UIViewController *leftSideMenuViewController = [storyboard instantiateViewControllerWithIdentifier:@"LeftSideMenuViewController"];
    
    [container setLeftMenuViewController:leftSideMenuViewController];
    
    [container setCenterViewController:tabBarController];
    

}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
#warning Tank 這裏進入到背景會登出
    if ([XMPPSharedInstance sharedInstance].state == 2) {
        self.isOpenApp = YES;
        xclient_fin();
    }
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    if (self.isOpenApp&&[XMPPSharedInstance sharedInstance].state == 0) {
        NSURL *baseURL = [NSURL URLWithString:MD_SERVER_API];
        AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
        NSOperationQueue *operationQueue = manager.operationQueue;
        
        [manager.reachabilityManager startMonitoring];
        
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case AFNetworkReachabilityStatusReachableViaWWAN:
                case AFNetworkReachabilityStatusReachableViaWiFi:
                    [operationQueue setSuspended:NO];
                    if (![[TelephonyInfo currentWifiName]hasPrefix:@"MDAP"]) {
                        NSLog(@"回到網路狀態");
                        //重新連線
                        double delayInSeconds = 1.0;
                        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                            if (delayInSeconds != 0.0) {
                                [[XMPPSharedInstance sharedInstance]login];
                            }
                        });
                    }
                    break;
                case AFNetworkReachabilityStatusNotReachable:
                    NSLog(@"無效網路");
                default:
                    [operationQueue setSuspended:YES];
                    break;
            }
        }];
    }


}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    
//    [self saveContext];
    [DBManage saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.ourpower.MooreDoll" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"MooreDoll" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"MooreDoll.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}
-(NSArray *)getRoster
{
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Roster" inManagedObjectContext:self.managedObjectContext];
    [fetch setEntity:entity];
    //朋友列表
    NSArray *array_myRoster =[self.managedObjectContext executeFetchRequest:fetch error:nil];

    return array_myRoster;
}


@end
